package com.cjg.gulimall.product.exception;

import com.cjg.common.exceptionCode.ExceptionCode;
import com.cjg.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;

@Slf4j
//@ControllerAdvice(basePackages = "com.cjg.gulimall.product.controller")
//@ResponseBody   RestControllerAdvice里面包含了两个
@RestControllerAdvice(basePackages = "com.cjg.gulimall.product.controller")
public class gulimallEXception {
    @ExceptionHandler(value = Exception.class)
    public R CException(MethodArgumentNotValidException e){
        log.error("数据校验出现的问题{},类型异常{}",e.getMessage(),e.getClass());

        HashMap<String, String> map = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach((i)->{
            map.put(i.getField(),i.getDefaultMessage());
        });
        return R.error(ExceptionCode.VAILD_EXCEPTION.getCode(),ExceptionCode.VAILD_EXCEPTION.getMsg()).put("data",map);
    }

    @ExceptionHandler(value=Throwable.class)
    public R hException(Throwable e){
        return R.error(ExceptionCode.UNKNOW_EXCEPTION.getCode(),ExceptionCode.UNKNOW_EXCEPTION.getMsg());
    }
}
